<template>
  <div class="login">
    <div class="login_panel">
      <h3 class="login_title">登录文鹿成教平台</h3>
      <el-form :model="ruleForm" ref="ruleForm" class="login-form">
        <el-form-item label prop="account" :rules="[{ required: true, message: '登录账号不能为空'}]">
          <el-input type="age" v-model.number="ruleForm.account" placeholder="请输入登录账号" clearable></el-input>
        </el-form-item>
        <el-form-item label prop="password" :rules="[{ required: true, message: '登录密码不能为空'}]">
          <el-input
            type="password"
            v-model.number="ruleForm.password"
            placeholder="请输入登录密码"
            clearable
          ></el-input>
        </el-form-item>
        <p v-if="loginError" class="login_error">账号或密码错误</p>
        <el-form-item>
          <el-button type="primary" class="login_btn" @click="handleLogin('ruleForm')">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
// 5-2输入时输入框有边框效果
// 5-4点击登录时如果账号密码错误给出提示
// 登录完成后进入首页
export default {
  name: 'Login',
  data () {
    return {
      loginError: false,
      ruleForm: {
        account: '615257196709099772',
        password: '099772',
        // account: '150770196808135221',
        // password: '135221',
        // account: '268406195508228157',
        // password: '228157',
      }
    }
  },
  methods: {
    handleLogin (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.doLogin()
        } else {
          return false
        }
      })
    },
    async doLogin () {
      const token = await this.getToken()
      if (token === '') {
        this.loginError = true
      } else {
        window.localStorage.setItem('access_token', token)
        this.$router.push('/index')
      }
    },
    getToken () {
      return this.$http.post('/student/login', {
        account_name: this.ruleForm.account,
        password: this.ruleForm.password
      }).then(res => {
        return res.access_token || ''
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .login {
    height: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    background-color: #d6e2fa;

    .login_panel {
      width: 400px;
      height: 420px;
      margin-right: 20%;
      border: 1px solid #ebebeb;
      box-sizing: border-box;
      padding: 40px 40px 80px;
      background-color: #ffffff;

      .login_title {
        text-align: center;
        color: #222222;
        font-size: 20px;
        padding-bottom: 19px;
        border-bottom: 1px solid #9dd521;
        margin-bottom: 30px;
      }

      .login-form {
        .el-input {
          :focus {
            border-color: #9dd521;
          }
        }
      }

      .login_btn {
        width: 100%;
        background-color: #9dd521;
        border-color: #9dd521;
        margin-top: 44px;
      }

      .login_error {
        font-size: 14px;
        color: #F47070;
      }
    }
  }
</style>
